<!--
 * @Date: 2024-07-12 09:59:48
 * @LastEditors: 陈俊宇 467724386@qq.com
 * @LastEditTime: 2025-01-03 17:20:50
-->
<template>
    <div class="form-container">
        <div class="header">
            <div>Live Chat</div>
            <img src="@/assets/close.png" class="close" alt="" @click="emit('close')" />
        </div>

        <div class="form">
            <el-form :model="state.form" :rules="state.rules" ref="ruleForm" label-position="left">
                <div class="title">
                    Dear customer! In order to provide better service, please fill in the following
                    information so that we can help you more quickly and accurately.
                </div>

                <el-form-item label="Name" prop="name">
                    <el-input
                        v-model="state.form.name"
                        @change="saveForm"
                        maxlength="25"
                        show-word-limit
                        size="large"
                    ></el-input>
                </el-form-item>

                <el-form-item label="Email" prop="email">
                    <el-input v-model="state.form.email" @change="saveForm" size="large"></el-input>
                </el-form-item>

                <el-form-item label="Country/Region" prop="country">
                    <el-select
                        v-model="state.form.country"
                        filterable
                        clearable
                        @change="saveForm"
                        size="large"
                    >
                        <el-option
                            v-for="item in countryList"
                            :key="item.englishAbbreviation"
                            :label="item.englishAbbreviation"
                            :value="item.englishAbbreviation"
                        />
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="Company" prop="company">
                    <el-input
                        v-model="state.form.company"
                        @change="saveForm"
                        maxlength="60"
                        show-word-limit
                        size="large"
                    ></el-input>
                </el-form-item>

                <el-form-item label="Company Identity" prop="companyType">
                    <el-select v-model="state.form.companyType" @change="saveForm" size="large">
                        <el-option
                            v-for="item in state.identityList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="Ticket Type">
                    <el-select
                        v-model="state.form.ticketTypeId"
                        @change="getTicketTypeName"
                        size="large"
                    >
                        <el-option
                            v-for="item in state.ticketTypeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="Ticket ID">
                    <el-input
                        v-model="state.form.ticketNo"
                        @change="saveForm"
                        maxlength="20"
                        show-word-limit
                        size="large"
                    ></el-input>
                </el-form-item>

                <el-form-item label="Product Model">
                    <el-select
                        v-model="state.form.productId"
                        filterable
                        remote
                        placeholder="Please enter keywords to search"
                        :remote-method="remoteMethod"
                        :loading="state.selectLoading"
                        class="select"
                        size="large"
                        @change="changeProduct"
                    >
                        <el-option
                            v-for="item in state.modelData"
                            :key="item.key"
                            :label="item.label"
                            :value="item.key"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="Serial Number" prop="productSn">
                    <el-input
                        v-model="state.form.productSn"
                        @change="saveForm"
                        maxlength="35"
                        show-word-limit
                        size="large"
                    ></el-input>
                </el-form-item> -->
            </el-form>
        </div>

        <div class="form-footer">
            <div class="checkbox">
                <el-checkbox v-model="state.checked" size="large" class="check" />
                I have read and agree to the
                <span class="privacy" @click="state.show = true">Privacy Policy</span>.
            </div>

            <div class="btn-list">
                <el-button @click="emit('close')" class="btn"> Cancel </el-button>
                <el-button type="primary" @click="submitForm(ruleForm)" class="btn">
                    Submit
                </el-button>
            </div>
        </div>

        <Privacy :show="state.show" @close="state.show = false"></Privacy>
    </div>
</template>

<script setup>
import { modelList, submitConsultForm, ticketProductCategory, ticketType } from '@/api'
import Privacy from '@/components/Privacy/Privacy.vue'
import { ElMessage } from 'element-plus'

import { onMounted, reactive, ref } from 'vue'

const props = defineProps({
    userId: {
        type: String,
        default: '',
    },
    countryList: {
        type: Array,
        default: () => {
            return []
        },
    },
})

const emit = defineEmits(['close', 'success'])

const ruleForm = ref()

const state = reactive({
    form: {},
    show: false,
    checked: false,
    category: [],
    selectLoading: false,
    modelData: [],
    ticketTypeList: [],
    identityList: [
        {
            label: 'Master-Distributor',
            value: '2',
        },
        {
            label: 'Reseller',
            value: '1',
        },
        {
            label: 'System Integrator',
            value: '0',
        },
        {
            label: 'Unknown',
            value: '3',
        },
    ],
    rules: {
        name: [
            {
                required: true,
                message: 'Name is required.',
                trigger: 'blur',
            },
        ],
        email: [
            {
                required: true,
                message: 'Email is required.',
                trigger: 'blur',
            },
            {
                type: 'email',
                message: 'Please enter a valid email address.',
                trigger: 'blur',
            },
        ],
        company: [
            {
                required: true,
                message: 'Company is required.',
                trigger: 'blur',
            },
        ],
        country: [
            {
                required: true,
                message: 'Country/Region is required.',
                trigger: 'change',
            },
        ],
        companyType: [
            {
                required: true,
                message: 'Company Identity is required.',
                trigger: 'change',
            },
        ],

        productSn: [
            {
                pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/,
                message: 'Product SN should contain letters and numbers.',
                trigger: 'blur',
            },
        ],
    },
})

onMounted(() => {
    getTicketProduct()
    getTicketType()

    const form = localStorage.getItem('ticketForm')

    if (form) {
        state.form = {
            ...JSON.parse(form),
            productId: '',
            productCategoryId: '',
            productCategoryName: '',
            productModel: '',
        }
    }
})

const submitForm = async (formEl) => {
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (state.checked) {
                const data = {
                    ...state.form,
                    userId: props.userId,
                }

                submitConsultForm(data).then((res) => {
                    ElMessage({
                        message: 'Your request was successfully submitted.',
                        type: 'success',
                    })
                    emit('close')
                    emit('success', res.data)
                })
            } else {
                ElMessage({
                    message: 'Please agree to the privacy policy.',
                    type: 'warning',
                })
            }
        }
    })
}

const getTicketType = () => {
    ticketType().then((res) => {
        state.ticketTypeList = res.data
    })
}

const getTicketProduct = async () => {
    ticketProductCategory().then((res) => {
        state.category = res.data
    })
}

const remoteMethod = (query) => {
    if (query) {
        state.selectLoading = true
        modelList(query).then((res) => {
            state.modelData = res.data.map((item) => {
                const category = state.category.find((e) => e.id === item.ticketProductCategoryId)
                return {
                    ...item,
                    key: `${item.ticketProductCategoryId}-${item.productModel}`,
                    label: `${category?.categoryName}/${item.productModel}`,
                    categoryName: category?.categoryName,
                }
            })

            state.selectLoading = false
        })
    } else {
        state.modelData = []
    }
}

const changeProduct = (key) => {
    const model = state.modelData.find((e) => e.key === key)
    state.form.productModel = model.productModel
    state.form.productCategoryId = model.ticketProductCategoryId
    state.form.productCategoryName = model.categoryName
}

const getTicketTypeName = (id) => {
    const data = state.ticketTypeList.find((e) => e.id === id)
    state.ticketTypeName = data.name

    saveForm()
}

const saveForm = () => {
    const data = JSON.stringify(state.form)
    localStorage.setItem('ticketForm', data)
}
</script>

<style lang="scss" scoped>
.form-container {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 880px;
    height: 80vh;
    z-index: 99;
    display: flex;
    flex-direction: column;

    .header {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        height: 72px;
        background: #ff8217;
        border-radius: 4px 4px 0px 0px;
        font-size: 20px;
        color: #ffffff;
        position: relative;
        box-sizing: border-box;

        .close {
            width: 16px;
            height: 16px;
            cursor: pointer;
            transition: 0.5s ease;

            &:hover {
                transform: scale(1.2);
            }
        }
    }

    .form {
        padding: 32px 32px 100px;
        box-shadow: var(--el-box-shadow-light);
        background: #fff;
        flex: 1;
        overflow-y: auto;

        :deep(.el-form-item) {
            margin-bottom: 24px;
        }

        :deep(.el-form-item__label) {
            font-size: 18px;
            width: 200px;
        }

        .title {
            font-size: 18px;
            color: #333333;
            margin-bottom: 30px;
        }

        .checkbox {
            margin-bottom: 20px;
            font-size: 14px;
            color: #606266;
            display: flex;
            align-items: center;

            .check {
                margin-right: 4px;
            }
            .privacy {
                color: #ff8217;
                cursor: pointer;
                margin-left: 4px;
            }
        }

        .btn-list {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            .btn {
                width: 100px;
                height: 40px;
            }
        }
    }
    .form-footer {
        width: 100%;
        position: absolute;
        left: 0;
        bottom: 0;
        background: #fff;
        padding-bottom: 20px;
        .checkbox {
            font-size: 16px;
            color: #606266;
            display: flex;
            align-items: center;
            padding-left: 230px;
            margin-bottom: 12px;

            .check {
                margin-right: 4px;
            }
            .privacy {
                color: #ff8217;
                cursor: pointer;
                margin-left: 4px;
            }
        }

        .btn-list {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            .btn {
                width: 100px;
                min-height: 40px;
            }
        }
    }
}
</style>
